var express = require('express');
var router = express.Router();
const { User } = require('../module/mondules');

// 文件上传所需要的模块
const multiparty = require('multiparty');
const fs = require('fs');

// 接收文件接口
router.post('/upload', async (req, res) => {
  //生成multiparty对象，并配置上传目标路径
  var form = new multiparty.Form({ uploadDir: './uploads/' });
  //上传后处理
  form.parse(req, function (err, fields, files) {
    var filesTmp = JSON.stringify(files, null, 2);
    if (err) {
      console.log('parse error: ' + err);
    } else {
      console.log('parse files: ' + filesTmp);
      var inputFile = files.file[0];
      var uploadedPath = inputFile.path; //上传文件的路径
      var dstPath = './uploads/' + inputFile.originalFilename;
      //重命名文件名
      fs.rename(uploadedPath, dstPath, function (err) {
        if (err) {
          console.log('rename error: ' + err);
        } else {
          console.log('rename ok');
          res.send({
            code: 200,
            message: '上传成功',
            data: {
              name: inputFile.originalFilename,
              url: `http://localhost:3000/uploads/${inputFile.originalFilename}`
            }
          })
        }
      })
    }
  })
})

// 文件列表
router.get('/filelist', async (req, res) => {
  fs.readdir('./uploads/', (err, files) => {
    if (err) {
      console.error(err);
      return;
    }
    const filelist = files.map(file => ({
      name: file,
      url: `http://localhost:3000/uploads/${file}`,
      size: fs.statSync(`./uploads/${file}`).size,
      type: file.split('.').pop()
    }));
    res.send({
      code: 200,
      message: '获取文件列表成功',
      data: filelist
    })
  })
})




// 获取用户信息
router.get('/userinfo', async (req, res) => {
  res.send({
    code: 200,
    message: '获取用户信息成功',
    data: req.user
  })
})


// 修改用户信息
router.post('/updateuserinfo', async (req, res) => {
  const { username, email, password, phone, userimg } = req.body;
  try {
    const user = await User.findOne({ _id: req.user._id }); // 查找用户
    if (!user) {
      return res.status(401).json({ message: '无效的用户' });
    }
    user.username = username;
    user.email = email;
    user.password = password;
    user.phone = phone;
    user.userimg = userimg;
    await user.save();
    res.send({
      code: 200,
      message: '修改成功',
      data: user
    })
  } catch (error) {
    res.send({
      code: 500,
      message: '修改失败',
      data: error
    })
  }
})


// 注册
router.post('/register', async (req, res) => {
  const { username, email, password, } = req.body;
  console.log(req.body);
  const user = new User({
    username, // 用户名
    email, // 邮箱
    password, // 密码
    // phone, // 手机号
  });
  await user.save();
  res.send({
    code: 200,
    message: '注册成功',
    data: user
  })
})


// 登录 邮箱+密码
router.post('/loginemail', async (req, res) => {
  const { email, password } = req.body;
  const user = await User.findOne({ email }); // 查找用户
  if (!user) {
    return res.status(401).json({ message: '无效的电子邮件' });
  }
  const isPasswordValid = () => {
    if (password === user.password) {
      return true
    } else {
      return false
    }
  } // 比较密码
  if (!isPasswordValid) {
    return res.status(401).json({ message: '无效的密码' });
  }
  res.send({
    code: 200,
    message: '登录成功',
    data: user
  })
})



module.exports = router;